package com.lagou.serialize;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
 * @ClassName: RpcEncoder
 * @Description: 编码器实现：(现在传输的是RpcRequest, 需要编码器将请求对象转换为适合于传输的格式)
 * @Version: v1.0.0
 * @Author: chendong
 * @Date: 2021/1/9
 * Modification History:
 * Date             Author      Version     Description
 * -------------------------------------------------------------
 * 2021/1/9         chendong       v1.0.0         创建
 */

public class RpcEncoder extends MessageToByteEncoder {


    private Class<?> clazz;
    private Serializer serializer;


    public RpcEncoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {

        if (clazz != null && clazz.isInstance(msg)) {
            byte[] bytes = serializer.serialize(msg);
            //读取消息的长度
            int dataLength = bytes.length;
            //先将消息长度写入，也就是消息头
            byteBuf.writeInt(dataLength);
            //消息体中包含我们要发送的数据
            byteBuf.writeBytes(bytes);
        }
    }
}
